import * as api from 'lib/constants/api'
import { get, post } from 'lib/net'

let wxShareConfig = async params => {
  if (window.wx.config.appId && window.wx.config.appId.length > 0) {
    shareConfig(params)
  } else {
    let url = api.WX_GET_SIGNATURE + window.location.href.split('#')[0]
    let res = await get(url)
    if (res.data) {
      let data = res.data
      window.wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: ['hideMenuItems', 'onMenuShareTimeline', 'onMenuShareAppMessage']
      })
      window.wx.ready(() => {
        shareConfig(params)
      })
      window.wx.error(err => {
        console.log(err.stack)
      })
    }
  }
}

let shareConfig = params => {
  window.wx.ready(() => {
    onMenuShareAppMessage(params.appMessage)
    onMenuShareTimeline(params.timeline)
  })
}

// http://green.shundaonetwork.com/mainText?postId=' + postDetail.ID
let onMenuShareAppMessage = params => {
  window.wx.onMenuShareAppMessage({
    title: params.title,
    type: 'link',
    link: params.link,
    desc: params.desc,
    imgUrl: 'http://green.shundaonetwork.com/icon.jpg',
    success: function () {
      shareSuccess(params)
    },
    cancel: function () {
    }
  })
}

let shareSuccess = params => {
  if (params.postId && params.userId) {
    post(api.SHARE_SUCCESS, params)
  }
}

  // title: postDetail.NoticeContent || '绿格子，绿色心情',
  // type: 'link',
  // link: 'http://green.shundaonetwork.com/mainText?postId=' + postDetail.ID,
  // imgUrl: 'http://green.shundaonetwork.com/icon.png',
// hareSuccess(postDetail.ID, userInfo.userId)
let onMenuShareTimeline = params => {
  window.wx.onMenuShareTimeline({
    title: params.title,
    type: 'link',
    link: params.link,
    imgUrl: 'http://green.shundaonetwork.com/icon.jpg',
    success: function () {
      shareSuccess(params)
    },
    cancel: function () {
    }
  })
}
module.exports = {
  wxShareConfig,
  shareConfig,
  onMenuShareAppMessage,
  onMenuShareTimeline
}
